<?php

namespace frontend\modules\mongodb\controllers;

use yii;
use yii\web\Controller;

/**
 * Default controller for the `mongodb` module
 */
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }
    
    public function actionTest()
    {
        $mongodb = Yii::$app->mongodb;
        $collection = $mongodb->getCollection ('hello');
        $data = $collection->find();//获取一条
        
        foreach($data as $val){
            var_dump($val);
        }
        echo "<pre>";   
    }
    
    //插入数据
    public function actionCreate()
    {
        $mongodb = Yii::$app->mongodb->getCollection ('hello');
        
        p($mongodb);
        
        /*
         * 返回 
         * object(MongoDB\BSON\ObjectId)#80 (1) {
              ["oid"]=>
              string(24) "5c9996998dfbc63de8005583"
            }
         * 
         */
        $res = $mongodb->insert([
            'name' => 'Sam',
            'age' => 30,
        ]);

        //$res->__toString() 获取字符串形id
        
        p($res);   
    }
    
    /**
     * 修改
     * 自动识别主键
     * 其他字段作为条件呢？
     */
    public function actionUpdate()
    {
        $mongodb = Yii::$app->mongodb->getCollection ('hello');
        
//         $data = [
//             '_id' => new \MongoDB\BSON\ObjectId("5c99a3668dfbc60418001d53"),
//             'name' => 'dasb',
//             'age' => 55
//         ];
//         //无主键，添加，有主键编辑
//         $res = $mongodb->save($data);
//         p($res); 

        //第二种方式
        
        $data = [
            'age' => '80'
        ];
        //返回受影响的记录数（可能0）
        $res = $mongodb->update(['name' => 'Sam'],$data);
        p($res);
        
    }
    
    /**
     * 删除一条
     * 删除多条
     */
    public function actionDelete()
    {
        $mongodb = Yii::$app->mongodb->getCollection ('hello');
        //返回 删除的记录数int
//         $res = $mongodb->remove(['name' => 'dasb']);
//         p($res);   
        
        //返回 删除的记录数int
        $res = $mongodb->remove(['_id' => new \MongoDB\BSON\ObjectId("5c9996998dfbc63de8005583")]);
        p($res);
    }
    
    
    
    
    
    
    
    
    
    
    
}
